﻿using CommonLib.Util;
using Oracle.ManagedDataAccess.Client;
using System.Xml.Linq;

namespace Oracle;

public class OracleHelp
{
    public static string RealType(string type)
    {
        if (TypeConvertor.IsBaseType(type)) return type;
        OracleConnection? conn = null;
        try
        {
            conn = new OracleConnection(ConstUtil.ConnectionString);
            conn.Open();
            if (type.Contains("%TYPE"))
            {
                var nty = type.Replace("%TYPE", "");
                var arr = nty.TrimSplit('.');
                var sql = "SELECT CASE WHEN DATA_TYPE IN('NUMBER','VARCHAR2','CHAR') THEN DATA_TYPE||'('||DATA_LENGTH||')' ELSE DATA_TYPE END FROM USER_TAB_COLUMNS WHERE TABLE_NAME='{0}' AND COLUMN_NAME='{1}'";
                using var cmd = new OracleCommand(string.Format(sql, arr[0], arr[1]), conn);
                return Convert.ToString(cmd.ExecuteScalar()) ?? type;
            }
            else
            {
                var sql = $"SELECT  OBJECT_TYPE  FROM USER_OBJECTS WHERE OBJECT_NAME='{type}'";
                using var cmd = new OracleCommand(sql, conn);
                return Convert.ToString(cmd.ExecuteScalar()) ?? type;
            }
        }
        catch { return type; }
        finally
        {
            conn?.Close();
            conn?.Dispose();
        }
    }
}
